package com.idroid.widget;

import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.idroid.R;

/**
 * Created by oushuhua
 * 底部统一交互式弹窗
 */
public abstract class BottomBasicPopup extends BasicPopup {
    private Activity attachActivity;
    private LinearLayout mRootView;

    public BottomBasicPopup(Activity context) {
        this(context, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    public BottomBasicPopup(Activity context, int height) {
        super(context, height);
        attachActivity = context;
        setAnimationStyle(R.style.bottompop_anim_style);
    }

    @Override
    public View getView() {
        mRootView = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.pop_bottomview, null);
        mRootView.findViewById(R.id.right_image).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        if (null != getContent()) {
            mRootView.addView(getContent());
        }
        return mRootView;
    }

    public abstract View getContent();


    public void show() {
        if (attachActivity == null) {
            attachActivity = (Activity) getContext();
        }

        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(attachActivity, 1.0f);
                attachActivity = null;
            }
        });

        View rootView = attachActivity.getWindow().getDecorView().findViewById(android.R.id.content);
        showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(attachActivity, 0.5f);
    }

    /**
     * 设置Activity背景透明度
     */
    private void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        //处理华为手机弹出后背景不变灰的问题
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        activity.getWindow().setAttributes(lp);
    }


    public BottomBasicPopup setTitle(String title){
        ((TextView)(mRootView.findViewById(R.id.title_text))).setText(title);
        return this;
    }

    public BottomBasicPopup setLeftClickCb(View.OnClickListener l){
        TextView leftTextView = (TextView) mRootView.findViewById(R.id.left_text);
        leftTextView.setVisibility(l==null?View.INVISIBLE:View.VISIBLE);
        leftTextView.setOnClickListener(l);
        return this;
    }
}
